<%@ page language="java" contentType="text/html;charset=utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!doctype html>
<!--[if lt IE 7]><html lang="en-CA" class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->
<!--[if IE 7]><html lang="en-CA" class="no-js lt-ie9 lt-ie8"><![endif]-->
<!--[if IE 8]><html lang="en-CA" class="no-js lt-ie9"><![endif]-->
<!--[if gt IE 8]><!-->
<html lang="en-CA" class="no-js">
<!--<![endif]-->
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>Guhappy</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<%
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
	%>
	<base href="<%=basePath%>">
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<link href="css/header.css" rel="stylesheet">
	<link href="css/common.css" rel="stylesheet">
	<link href="css/typeahead_css.css" rel="stylesheet">
	<style type="text/css">
		button.dropdown-toggle
		{
			width:120px;
		}
		
		/* MULTI-LEVEL DROPDOWNS FOR BOOTSTRAP */
		.dropdown-menu .sub-menu {
			left: 100%;
			position: absolute;
			top: 0;
			visibility: hidden;
			margin-top: -1px;
		}

		.dropdown-menu li:hover .sub-menu {
			visibility: visible;
			display: block;
		}
	</style>
</head>
<body>
	<jsp:include page="header.jsp" />
	<div class="row" style="margin-top:80px">
		<div class="col-md-4 col-md-offset-4" style="text-align:center">
			<img src="images/guhappy.jpg" />
		</div>
	</div>
	
	<div class="row" style="margin-top:20px">
		<s:if test="hasActionErrors()">
		   <div class="alert alert-error alert alert-error col-xs-12 col-md-6 col-md-offset-3">
		   	<button data-dismiss="alert" type="button" class="close">×</button><strong>Error! </strong>
		    <s:actionerror/>
		   </div>
		</s:if>
		<div class="col-xs-12 col-md-6 col-md-offset-3" >
			<form class="form-inline" role="form" action="stock.action">
				<div class="col-md-10" style="padding-right:0px;">
					<div class="input-group">
						<span class="input-group-btn" style="vertical-align:top">
							<div class="btn-group">
								<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
									<span id="areaCode">Canada</span>
									<span class="caret"></span>
								</button>
								<ul class="dropdown-menu">
									<li><a href="javascript:void(0)">United States</a></li>
									<li><a href="javascript:void(0)">Canada</a></li>
									<li><a href="javascript:void(0)">North America</a></li>
									<li><a href="javascript:void(0)">China</a></li>
									<li><a href="javascript:void(0)">Hongkong</a></li>
									<li><a href="javascript:void(0)">Taiwan</a></li>
									<li><a href="javascript:void(0)">Singapore</a></li>
									<li><a href="javascript:void(0)">Austrilia</a></li>
									<li><a href="javascript:void(0)">London</a></li>
									<li><a href="javascript:void(0)">Korea</a></li>
									<!-- <li role="presentation" class="divider"></li> -->
								</ul>
								<input type="hidden" id= "area" name="area" value="Canada"/>
							</div>
						</span>
						<div id="the-basics">
						<input type="text" name="stock" autocomplete="off" class="typeahead" id="stock" data-rules="required:true" placeholder="Please enter company name or symbol.">
						</div>
					</div> <!--/input-group -->
				</div>
				<div class="col-xs-12 col-md-2"  style="padding-left:0px;">
					<button class="btn btn-default" type="submit" style="border-radius:0px">Search<i class="icon-search"></i></button>
				</div>
			</form>
		</div><!-- /.col-md-6 -->
	</div>

	<div class="row" style="margin-top:20px">
		<div class="col-xs-12 col-md-8 col-md-offset-2">
			<div id="popularStocks" ></div>
		</div>
	</div>
	<div class="row">
		<div class="col-xs-11 col-md-6 col-xs-offset-1 col-md-offset-3">
			<div id='summery' style="display: none;">
				<div class="row">
					<div class="col-md-7">
						<p>
						<h3>
							<b id='name'>a</b>
						</h3>
					</div>
				</div>
				<div class="container">
					<div class="row">
						<div class="col-md-2">
							<h1 id='currentPrice'>b</h1>
						</div>
						<div class="col-md-1">
							<br>
							<br>
							<span id='change'>b</span>
							<span id='valueChange'>b</span>
						</div>
						<div class="col-md-3">
							Vote:<span id='vote'>b</span><br>
							52 weeks high:<span id="YearHigh">123</span><br>
							52 weeks low:<span id="YearLow">12</span><br>
							Three months return:<span id='threeMonReturn'>b</span><br>
						</div>
					</div>
				</div><!--/ .container-->
			</div><!--/ #summery-->
		</div><!--/ .col-md-6 .col-md-offset-3-->
		<div class="col-md-2 pagination-centered">
			<!--<img src="./image/howtoplay.jpg" hidden="true">-->
		</div>
	</div><!--/ row-fluid -->
	
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bar.js"></script>
<script type="text/javascript" src="js/header.js"></script>
<script src="js/typeahead_bundle.js"></script>
<script>
var usaArr = [];
var sourceArr = [];
var northArr = [];
var chinaArr = [];
(function($) {
    function getStock(opts, type, complete) {
        var defs = {
            desc: false,
            baseURL: 'http://query.yahooapis.com/v1/public/yql?q=',
            query: {
                quotes: 'select * from yahoo.finance.quotes where symbol = "{stock}" | sort(field="{sortBy}", descending="{desc}")',
                historicaldata: 'select * from yahoo.finance.historicaldata where symbol = "{stock}" and startDate = "{startDate}" and endDate = "{endDate}"'
            },
            suffixURL: {
                quotes: '&env=store://datatables.org/alltableswithkeys&format=json&callback=?',
                historicaldata: '&env=store://datatables.org/alltableswithkeys&format=json&callback=?'
            }
        };
        opts = opts || {};
        if (!opts.stock) {
            complete('No stock defined');
            return;
        }
        var query = defs.query[type]
        .replace('{stock}', opts.stock)
        .replace('{sortBy}', defs.sortBy)
        .replace('{desc}', defs.desc)
        .replace('{startDate}', opts.startDate)
        .replace('{endDate}', opts.endDate)
       var url = defs.baseURL + query + (defs.suffixURL[type] || '');
        $.getJSON(url, function(data) {
            var err = null;
            if (!data || !data.query) {
                err = true;
            }
            complete(err, !err && data.query.results);    });
    }
    window.getStock = getStock;
})(jQuery);

Date.prototype.yyyymmdd = function() {        
    var yyyy = this.getFullYear().toString();                                    
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based        
    var dd  = this.getDate().toString();            
    return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
}; 
endDate = new Date();
startDate = new Date();
startDate.setDate(endDate.getDate()-32);

$(function() {
	// Setup drop down buttons.
	$(".dropdown-menu li a").on("click", function(event){
		$("#areaCode").text($(this).text());
		$("#areaCode").val($(this).text());
		$("#area").val($(this).text());
		$("#stock").val("");
		$('#the-basics .typeahead').typeahead('destroy');
		if ($(this).text() == 'United States')
			{
			$('#the-basics .typeahead').typeahead({
				  hint: true,
				  highlight: true,
				  minLength: 2,
				},
				{
				  name: 'usaArr',
				  displayKey: 'value',
				  source: substringMatcher(usaArr)
				}); 
			}
		else if  ($(this).text() == 'North America')
			{
			$('#the-basics .typeahead').typeahead({
				  hint: true,
				  highlight: true,
				  minLength: 2,
				},
				{
				  name: 'northArr',
				  displayKey: 'value',
				  source: substringMatcher(northArr)
				}); 
			}
		else if  ($(this).text() == 'China')
		{
		$('#the-basics .typeahead').typeahead({
			  hint: true,
			  highlight: true,
			  minLength: 2,
			},
			{
			  name: 'chinaArr',
			  displayKey: 'value',
			  source: substringMatcher(chinaArr)
			}); 
		}else {
				sourceArr = [];
				$.ajax({
			        type: "POST",
			        dataType: 'json',
			        url: 'jsonstocks.action',
			        data: {'area':$(this).text()},
			        success: function(data) {
						for (var i = 0; i < data.reloadList.length; i++) {
			           sourceArr.push(data.reloadList[i].name);
			           }
			        },
			        error: function (request, status, error) {
			        }

			      });
				$('#the-basics .typeahead').typeahead({
					  hint: true,
					  highlight: true,
					  minLength: 1,
					},
					{
					  name: 'sourceArr',
					  displayKey: 'value',
					  source: substringMatcher(sourceArr)
					}); 
			}
		$.ajax({
	        type: "POST",
	        dataType: 'json',
	        url: 'jsonrollingstocks.action',
	        data: {'area':$(this).text()},
	        success:function(data){
				var html = '';
				for(var i in data.stock) {
					var inner = '<span class="popularStock" style="color:';
					var stock = data.stock[i];
					if(stock.change.indexOf('-') > -1) {
						inner += '#AA1111;">';
					}
					else {
						inner += '#228822;">';
					}
					inner += stock.symbol + ' ' + stock.change + '</span>&nbsp;&nbsp;&nbsp;&nbsp;';
					html += inner;
				}
				$("#popularStocks").html(function(i,origHtml){
					return html; 
				});
				
				$("#popularStocks").marquee();
				
				var showing = false;
				var symbol = "";
				var currentSymbol = "";
				$(".popularStock").mouseover(function(){
					var value = $(this).text();
					var i = value.indexOf(' ');
					symbol = value.substring(0, i);
					if( currentSymbol == symbol) {
						sybmol = "";
					}
					if(showing) {
						return;
					}
					showing = true;
					showSummary(symbol);
					symbol = "";
				}).mouseout(function(){
					$("#summery").fadeOut("fast", function() {
						currentSymbol = "";
						showing = false;
						showSummary(symbol);
						symbol = "";
					});
				});
			}, 
	        error: function (request, status, error) {
	        }

	    });

	});
	
	$.ajax({
        type: "POST",
        dataType: 'json',
        url: 'jsonstocks.action',
        data: {'area':'Canada'},
        success: function(data) {
           for (var i = 0; i < data.reloadList.length; i++) {
           sourceArr.push(data.reloadList[i].name);
           }
        },
        error: function (request, status, error) {
        }

      });
	
	$.ajax({
        type: "POST",
        dataType: 'json',
        url: 'jsonstocks.action',
        data: {'area':'North America'},
        success: function(data) {
           for (var i = 0; i < data.reloadList.length; i++) {
        	   northArr.push(data.reloadList[i].name);
           }
        },
        error: function (request, status, error) {
        }

      });
	
	$.ajax({
        type: "POST",
        dataType: 'json',
        url: 'jsonstocks.action',
        data: {'area':'China'},
        success: function(data) {
           for (var i = 0; i < data.reloadList.length; i++) {
        	   chinaArr.push(data.reloadList[i].name);
           }
        },
        error: function (request, status, error) {
        }

      });
	
	$.ajax({
        type: "POST",
        dataType: 'json',
        url: 'jsonstocks.action',
        data: {'area':'United States'},
        success: function(data) {
           for (var i = 0; i < data.reloadList.length; i++) {
           usaArr.push(data.reloadList[i].name);
           }
        },
        error: function (request, status, error) {
        }

      });
	
	$.ajax({
        type: "POST",
        dataType: 'json',
        url: 'jsonrollingstocks.action',
        data: {'area':'Canada'},
        success:function(data){
			var html = '';
			for(var i in data.stock) {
				var inner = '<span class="popularStock" style="color:';
				var stock = data.stock[i];
				if(stock.change.indexOf('-') > -1) {
					inner += '#AA1111;">';
				}
				else {
					inner += '#228822;">';
				}
				inner += stock.symbol + ' ' + stock.change + '</span>&nbsp;&nbsp;&nbsp;&nbsp;';
				html += inner;
			}
			
			$("#popularStocks").html(function(i,origHtml){
				return html; 
			});
			
			$("#popularStocks").marquee();
			
			var showing = false;
			var symbol = "";
			var currentSymbol = "";
			$(".popularStock").mouseover(function(){
				var value = $(this).text();
				var i = value.indexOf(' ');
				symbol = value.substring(0, i);
				if( currentSymbol == symbol) {
					sybmol = "";
				}
				if(showing) {
					return;
				}
				showing = true;
				showSummary(symbol);
				symbol = "";
			}).mouseout(function(){
				$("#summery").fadeOut("fast", function() {
					currentSymbol = "";
					showing = false;
					showSummary(symbol);
					symbol = "";
				});
			});
		}, 
        error: function (request, status, error) {
        }

    });

});


var substringMatcher = function(strs) {
	  return function findMatches(q, cb) {
	    var matches, substrRegex;

	    // an array that will be populated with substring matches
	    matches = [];

	    // regex used to determine if a string contains the substring `q`
	    substrRegex = new RegExp(q, 'i');

	    // iterate through the pool of strings and for any string that
	    // contains the substring `q`, add it to the `matches` array
	    $.each(strs, function(i, str) {
	      if (substrRegex.test(str)) {
	        // the typeahead jQuery plugin expects suggestions to a
	        // JavaScript object, refer to typeahead docs for more info
	        matches.push({ value: str });
	      }
	    });

	    cb(matches);
	  };
	};

	$('#the-basics .typeahead').typeahead({
	  hint: true,
	  highlight: true,
	  minLength: 1,
	},
	{
	  name: 'sourceArr',
	  displayKey: 'value',
	  source: substringMatcher(sourceArr)
	});  
	
function showSummary(querySymbol) {
	var colorDrop = 'color:#AA1111';
	var colorRise = 'color:#228822';
	currentSymbol = querySymbol;
	var currentOpen;
	var priorClose;
	if(querySymbol.length > 0 ){
		getStock({ stock: currentSymbol }, 'quotes', function(err, data) {
			$("#summery").fadeIn("fast");
			$("#name").text(function(i,origText){
				return data.quote.Symbol; 
			});
			 var $valueChange = $("#valueChange");
			if(data.quote.ChangeRealtime.indexOf('-')> -1) {
				$valueChange.attr('style', colorDrop);
			}
			else {
				$valueChange.attr('style', colorRise);
			}
			$valueChange.text(function(i,origText){
				return data.quote.ChangeRealtime; 
			});
			
			var $change = $("#change");
			if(data.quote.ChangeinPercent.indexOf('-')> -1) {
				$change.attr('style', colorDrop);
			}
			else {
				$change.attr('style', colorRise);
			}
			$change.text(function(i,origText){
				return data.quote.ChangeinPercent; 
			});
	
			$("#YearHigh").text(function(i,origText){
				return data.quote.YearHigh; 
			});
			$("#YearLow").text(function(i,origText){
				return data.quote.YearLow; 
			});
			
			$("#currentPrice").text(function(i,origText){
				return data.quote.BidRealtime;
			}); 
			currentOpen = data.quote.Open;
            getStock({ stock: currentSymbol, startDate: startDate.yyyymmdd(), endDate: startDate.yyyymmdd()}, 'historicaldata', function(err, data) {
            	   priorClose = data.quote.Close;
            	   $("#threeMonReturn").text(function(i,origText){
       				return Math.floor((currentOpen/priorClose) * 100)+'%'; 
       			});
			});
			
			/* $("#vote").text(function(i,origText){
				return data.vote; 
			}); */

		});

	}
	}
</script>

</html>